const _path = require("node:path");
const fs = require("node:fs");
const { get_fst_file, get_full_path, move } = require("../utils/file_tool");
const { BaseCommand } = require("./base");
const { default: imagemin } = require('imagemin');
const { default: imageminPngquant } = require('imagemin-pngquant');
const { default: imageminMozjpeg } = require('imagemin-mozjpeg');

class CompressCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const src = get_fst_file(data.src);
        const dstFile = get_full_path(data.dst, "FILE");
        const dstDir = _path.dirname(dstFile);
        const dstName = _path.basename(dstFile);
        const tmpFolder = _path.join(this.shareData.AUTOMATOR_SCRATCH, "comporess");
        if (!fs.existsSync(tmpFolder)) {
            fs.mkdirSync(tmpFolder, { recursive: true });
        }
        const quality = data.options?.quality || 80;
        await imagemin([src], {
            destination: tmpFolder,
            plugins: [
                imageminMozjpeg({ quality: quality }), // 压缩 JPG 图片
                imageminPngquant({
                    quality: [0.6, quality / 100],
                })
            ]
        });
        const compressedFile = _path.join(tmpFolder, _path.basename(src));
        fs.copyFileSync(compressedFile, _path.join(dstDir, dstName));
        fs.unlinkSync(compressedFile);
        // const sharp = require("sharp");
        // const options = data.options;
        // const fileContent = readFileSync(src);
        // await sharp(fileContent)[format](options).toFile(dst);
    }
}

module.exports = {
    CompressCommand,
};
